import path = require('path');
import { chromium } from 'playwright';
import { BrowserConfig } from './config/browser.config';
import { parseTime } from './utils';

export default class GlobalService {
  constructor() {}

  async onInit() {
    // 挂载log输出路径
    const logPath = path.join(
      __dirname,
      `../logs/${parseTime(new Date().getTime())}`
    );
    // 挂载浏览器
    const browser = await chromium.launch(BrowserConfig.browser);
    // 挂载上下文
    const context = await browser.newContext({
      ...BrowserConfig.context,
      recordVideo: {
        dir: `${logPath}/videos`,
        size: { width: 1280, height: 800 },
      },
    });
    // 打开新页面
    const page = await context.newPage();
    // 存在全局下面方便获取
    globalThis.BrowserBasics = {
      logPath,
      browser,
      context,
      page,
      closeContext: async () => {
        await context.close();
      },
      closeBrowser: async () => {
        await browser.close();
      },
    };
  }
}
